package client;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {

	private Socket s;
	
	/**
	 * 构造函数，同时连接上服务器
	 * @param url 服务器地址
	 * @param port 服务器端口号
	 */
	public Client(String url, int port) {
		try {
			s = new Socket(url, port);
			
			System.out.println("Connect to " + url + " at " + port + "successfully!");
			System.out.println("Enter bye to exit.");
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 向服务器端发送信息
	 * @param message 所要发送的信息
	 * @return
	 */
	public boolean sendMessage(String message) {
		if (!s.isClosed()) {
			try {
				PrintWriter out = new PrintWriter(s.getOutputStream());
				System.out.println("> echo :" + message);
				out.println(message);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return true;
		}
		
		System.out.println("Connection shut down.");
		return false;
	}
	
	/**
	 * 关闭连接
	 */
	public void closeConnection() {
		try {
			this.s.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		Client client = new Client("127.0.0.1", 8199);
		
		boolean done = false;
		Scanner in = new Scanner(System.in);
		while (in.hasNextLine() && !done) {
			String line = in.nextLine();
			done = !(client.sendMessage(line));
		}
	}
}
